package com.liu.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liu.model.Data;
import com.liu.model.DataDao;
import com.liu.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/data")
public class DataServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        resp.setContentType("application/json; charset=utf8");
        if (session == null) {
            Data data = new Data();
            resp.getWriter().write(objectMapper.writeValueAsString(data));
            return;
        }
        User user = (User) session.getAttribute("user");
        int userId = user.getUserId();
        if (user == null) {
            user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        DataDao dataDao = new DataDao();
        Data data = dataDao.selectById(userId);

        resp.getWriter().write(objectMapper.writeValueAsString(data));
    }
}
